<?php
require_once 'business/TrendsBusiness.class.php';
require_once 'business/UserBusiness.class.php';

/**
 * Controlador para la pagina de busqueda de eventos en GCalendar
 *
 * @package GCalFaces
 * @subpackage Controllers
 */
class RealTwitter_ControllerMain extends RealTwitter_Controller{

	//Variables
	protected $consumer_key = 'ZUZmAabG4HkeXBYDfgJGQ';
	protected $consumer_secret = 'Y5ypB8XObh9rg1oxD5YGIFM3DVirKWePQJt9yHY';
	protected $user = null;
	protected $accesoDenegado = false;
	protected $autentificado = false;
	protected $twitterObj = null;

	/**
	 * Constructor de la clase
	 *
	 */
	public function __construct($action=self::WELCOME_ACCION)
	{
		switch ($action) {
			case self::WELCOME_ACCION:
			case self::TRENDS_ACCION:
			case self::USER_TIMELINE_ACCION:
			case self::HOME_TIMELINE_ACCION:
			case self::TRENDS_BY_WOEID_AJAX:
				$this->action = $action;
				break;
			default:
				throw new Exception('Accion no reconocida en el constructor: '.$action);;
				break;
		}
	}

	/**
	 * Ejecuta la accion establecida
	 *
	 */
	public function execute(){
		switch ($this->action) {
			case self::WELCOME_ACCION:
				$this->welcome();
				break;
			case self::TRENDS_ACCION:
				$this->trends();
				break;
			case self::USER_TIMELINE_ACCION:
				$this->userTimeLine();
				break;
			case self::HOME_TIMELINE_ACCION:
				$this->homeTimeLine();
				break;
			case self::TRENDS_BY_WOEID_AJAX:
				$woeid = $_GET['woeidSelected'];
				$this->getTrendsByWoeidAjax($woeid);
				break;
			default:
				throw new Exception('Accion no reconocida en execute: '.$this->action);;
				break;
		}
	}


	//ACCIONES
	/**
	* Muestra la pantalla principal del sistema
	*
	*/
	private function welcome(){
		//comprobamos credenciales
		$this->comprobarCredenciales();
		$params = $this->addHeaderParams();

		$view = new RealTwitter_ViewMain($params);
		//Se define el template ha utilizar
		$view->setTemplate('index.tpl');
		$view->showPage();
	}
	private function trends(){
		$this->comprobarCredenciales();
		$params = $this->addHeaderParams();
		if ($this->autentificado){
			//comprobamos credenciales
			$trendsBusiness = new TrendsBusiness($this->user, $this->twitterObj);

			$trendLocal = $trendsBusiness->getTrends();
			$locationsAvailable = $trendsBusiness->getTrendsAvailable();
				
			$params['trends'] = $trendLocal->trends;
			$params['locationsAvailable'] = $locationsAvailable;
		}

		$view = new RealTwitter_ViewMain($params);
		//Se define el template ha utilizar
		$view->setTemplate('trends.tpl');
		$view->showPage();
	}
	/**
	 * @return TimeLine
	 * Enter description here ...
	 */
	private function userTimeLine(){
		//comprobamos credenciales
		$this->comprobarCredenciales();
		$params = $this->addHeaderParams();
		if ($this->autentificado){
			$userTimeLine = $this->obtenerTimeLine(self::USER_TIMELINE);
			$params['userTwits'] = $userTimeLine->twits;
		}

		$view = new RealTwitter_ViewMain($params);
		//Se define el template ha utilizar
		$view->setTemplate('userTimeLine.tpl');
		$view->showPage();
	}
	/**
	 * @return TimeLine
	 * Enter description here ...
	 */
	private function homeTimeLine(){
		$this->comprobarCredenciales();
		$params = $this->addHeaderParams();
		if ($this->autentificado){
			$publicTimeLine = $this->obtenerTimeLine(self::HOME_TIME_LINE);
			$params['publicTwits'] = $publicTimeLine->twits;
		}

		$view = new RealTwitter_ViewMain($params);
		//Se define el template ha utilizar
		$view->setTemplate('publicTimeLine.tpl');
		$view->showPage();
	}


	//AJAX
	private function getTrendsByWoeidAjax($woeid){
		$this->comprobarCredenciales();
		if ($this->autentificado){
			//comprobamos credenciales
			$trendsBusiness = new TrendsBusiness($this->user, $this->twitterObj);

			$trendLocal = $trendsBusiness->getTrends($woeid);
			$params['trends'] = $trendLocal->trends;
		}

		$view = new RealTwitter_ViewMain($params);
		//Se define el template ha utilizar
		$view->setTemplate('trendsAjax.tpl');
		$view->showPage();
	}


	//FUNCIONES AUXILIARES
	private function comprobarCredenciales(){
		$this->twitterObj = new EpiTwitter($this->consumer_key, $this->consumer_secret);

		if (isset($_GET['oauth_token']) || ( isset($_SESSION['oauth_token']) && isset($_SESSION['oauth_token_secret']) )){
			//Acceso
			if (!isset($_SESSION['oauth_token']) || !isset($_SESSION['oauth_token_secret'])){
				//Viene de twitter
				$this->twitterObj->setToken($_GET['oauth_token']);
				$token = $this->twitterObj->getAccessToken();
				$_SESSION['oauth_token'] = $token->oauth_token;
				$_SESSION['oauth_token_secret'] = $token->oauth_token_secret;

				$this->twitterObj->setToken($token->oauth_token, $token->oauth_token_secret);
			} else {
				//Ya nos dio acceso
				$this->twitterObj->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
			}
			$this->user = $this->twitterObj->get_accountVerify_credentials();

			$this->autentificado = true;
		} elseif (isset($_GET['denied'])){
			$this->accesoDenegado = true;
		}else{
			$this->autentificado = false;
		}
	}
	private function obtenerTimeLine($tipoTimeLine){
		$parametros = array('id'=>$this->user->id);
		if ($tipoTimeLine == self::USER_TIMELINE){
			$timeLineTwitter = $this->twitterObj->get_statusesUser_timeline($parametros);
		}else{
			$timeLineTwitter = $this->twitterObj->get_statusesHome_timeline($parametros);
		}
		if ($timeLineTwitter != null && $timeLineTwitter->response != null){
			$twits = array();
			$timeLine = new TimeLine();
			foreach ($timeLineTwitter->response as $key => $value){
				$twit = new Twitt($value);
				//add the twit to the array
				array_push($twits, $twit);
			}

			$timeLine->twits = $twits;
		}
		return $timeLine;
	}

	private function addHeaderParams($args = Array()){

		if ($this->autentificado){
			$args['error'] = false;
			$args['logged_in'] = true;
			$args['nombreUsuario'] = $this->user->name;
			$args['seguidores'] = $this->user->followers_count;
			$args['situacion'] = $this->user->location;
		}else{
			if ($this->accesoDenegado){
				$args['error'] = true;
				$args['logged_in'] = true;
			}else{
				$args['logged_in'] = false;
				$args['urlLogin'] = $this->twitterObj->getAuthorizationUrl();
			}
		}
		return $args;
	}
}
?>